package login

import (
	"Student_Mental/DBconfing"
	_ "database/sql"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

var jwtkey = []byte("www.topgoer.com")

type Claims struct {
	StuName string
	Status  string
	Id      string
	Number  string
	jwt.StandardClaims
}

// CheckUses
// @Tags 登入
// @summary 登入验证
// @Param status formData  string false "状态：老师/学生"
// @Param number formData  int false "学号/工号"
// @Param password formData  string false "密码"
// @Router /login [post]
func CheckUses(c *gin.Context) {
	status := c.PostForm("status")
	number, _ := strconv.Atoi(c.PostForm("number"))
	password := c.PostForm("password")
	sqlDb, _ := DBconfing.Mysql()

	//查询后的数据
	var name, sqlpassword string
	var id string
	var err error
	//登入判断
	if status == "学生" {
		err = sqlDb.QueryRow("SELECT id,student_name,student_password FROM student where student_number = ?", number).Scan(&id, &name, &sqlpassword)

	} else {
		err = sqlDb.QueryRow("SELECT id,teacher_name,teacher_password FROM teacher where teacher_number = ?", number).Scan(&id, &name, &sqlpassword)
	}
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"res":  "没找到用户",
		})
		return
	}

	//核对用户密码
	if sqlpassword != password {
		c.JSON(200, gin.H{
			"code": 0,
			"res":  "密码错误",
		})
		return
	}
	//成功登入
	token, _ := CreateToken(name, status, c.PostForm("number"), id) //生成token
	c.SetCookie("Token", token, 3600*24, "/", "127.0.0.1", false, false)
	c.SetCookie("Name", name, 3600*24, "/", "127.0.0.1", false, false)
	c.SetCookie("number", c.PostForm("number"), 3600*24, "/", "127.0.0.1", false, false)
	c.SetCookie("Status", status, 3600*24, "/", "127.0.0.1", false, false)
	c.SetCookie("Id", id, 3600*24, "/", "127.0.0.1", false, false)
	c.JSON(200, gin.H{
		"code":  1,
		"res":   status + "登入成功",
		"Token": token,
	})
	sqlDb.Close()
}

// EXitLogin
// @Tags 登入
// @summary 退出
// @Router /exit [get]
func EXitLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.SetCookie("Token", "", -1, "/", "127.0.0.1", false, false)
		c.SetCookie("Name", "", -1, "/", "127.0.0.1", false, false)
		c.SetCookie("number", "", -1, "/", "127.0.0.1", false, false)
		c.SetCookie("Status", "", -1, "/", "127.0.0.1", false, false)
		c.SetCookie("Id", "", -1, "/", "127.0.0.1", false, false)
		c.Redirect(http.StatusMovedPermanently, "/login")
	}
}

// CreateToken 创建token
func CreateToken(stu string, sta string, num string, Id string) (tokenString string, err error) {
	expireTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		StuName: stu,
		Status:  sta,
		Id:      Id,
		Number:  num,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), //过期时间
			IssuedAt:  time.Now().Unix(),
			Issuer:    "127.0.0.1",  // 签名颁发者
			Subject:   "user token", //签名主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// fmt.Println(token)
	tokenString, err = token.SignedString(jwtkey)
	if err != nil {
		fmt.Println(err)
	}
	return tokenString, err
}

// ParseToken 解析token
func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	Claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtkey, nil
	})
	return token, Claims, err
}
